package com.qsd.TeacherSystem.Service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.qsd.TeacherSystem.Service.TeacherService;
import com.qsd.TeacherSystem.compnent.MyClient;
import com.qsd.TeacherSystem.dao.TeacherDao;
import com.qsd.TeacherSystem.dao.UserHeadersDao;
import com.qsd.TeacherSystem.exception.BizException;
import com.qsd.common.enums.ResultStatus;
import com.qsd.common.po.Teacher;
import com.qsd.common.pojo.TeacherEntity;
import com.qsd.common.pojo.UserHeadsEntity;
import com.qsd.common.util.SmToken;
import com.qsd.common.vo.SmResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class TeacherServiceImpl implements TeacherService {

    @Resource
    private TeacherDao teacherDao;
    @Resource
    private UserHeadersDao userHeadersDao;
    @Resource
    private MyClient myClient;
    @Resource
    private SmToken smToken;

    @Override
    public Teacher login(String username, String password) {

        LambdaQueryWrapper<TeacherEntity> wrapper = new LambdaQueryWrapper<TeacherEntity>()
                .eq(TeacherEntity::getUsername, username)
                .eq(TeacherEntity::getPassword, password);
        TeacherEntity teacherEntity = teacherDao.selectOne(wrapper);
        if (ObjectUtil.isNotNull(teacherEntity)) {
            Teacher teacher = new Teacher();
            BeanUtil.copyProperties(teacherEntity, teacher);
            LambdaQueryWrapper<UserHeadsEntity> uh = new LambdaQueryWrapper<UserHeadsEntity>()
                    .eq(UserHeadsEntity::getUserName, username)
                    .orderByDesc(UserHeadsEntity::getCreateTime)
                    .last("limit 1");
            UserHeadsEntity userHeadsEntity = userHeadersDao.selectOne(uh);
            if (ObjectUtil.isNotNull(userHeadsEntity)){
                String userUrl = userHeadsEntity.getUserUrl();
                log.info("用户头头像信息:userUrl:{}", userUrl);
                teacher.setUserUrl(userUrl);
            }
            return teacher;
        }
        return null;
    }

    @Override
    @Transactional
    public Integer register(Teacher teacher) {

        LambdaQueryWrapper<TeacherEntity> eq = new LambdaQueryWrapper<TeacherEntity>()
                .eq(TeacherEntity::getUsername, teacher.getUsername());
        TeacherEntity obj = teacherDao.selectOne(eq);
        if (ObjectUtil.isNull(obj)) {
            throw new BizException(ResultStatus.USER_NAME_USED_ERROR);
        }
        TeacherEntity teacherEntity = new TeacherEntity();
        BeanUtil.copyProperties(teacher, teacherEntity);
        return teacherDao.insert(teacherEntity);
    }


    /**
     * 修改用户信息
     * @param teacher
     * @param request
     * @return
     */
    @Override
    @Transactional
    public boolean updateInfo(Teacher teacher, HttpServletRequest request) {
        log.info("teacher:{}", teacher);
        TeacherEntity teacherEntity = new TeacherEntity();
        BeanUtil.copyProperties(teacher, teacherEntity);
        log.info("TeacherEntity:{}", teacherEntity);
        boolean update = new LambdaUpdateChainWrapper<>(teacherDao)
                .eq(TeacherEntity::getUsername, teacher.getUsername())
                .update(teacherEntity);
        if (update) {
            LambdaQueryWrapper<TeacherEntity> eq = new LambdaQueryWrapper<TeacherEntity>()
                    .eq(TeacherEntity::getUsername, teacher.getUsername());
            Teacher entity = teacherDao.findTeacherInfomation(eq);
            this.reSetCurrentSession(request, null, entity);
        }
        return update;
    }

    @Override
    public boolean uploadFileForHeader(MultipartFile multipartFile, String username, HttpServletRequest request) {
        Map<String, Object> headerMap = new HashMap<>();
        headerMap.put("Authorization", Base64.decodeStr(smToken.getToken()));
        headerMap.put("User-Agent", smToken.getUseragent());
        SmResp s;
        String url;
        boolean flag;
        try {
            s = myClient.helloForest(headerMap, multipartFile);//当前接口调用第三方图床接口,需要连接网络
        } catch (Exception e) {
            log.info("网络异常", e);
            throw new BizException(ResultStatus.HEADER_NET_ERROR);
        }
        if (s.getSuccess()) {
            SmResp.SmData data = s.getData();
            url = data.getUrl();
            log.info("url:{}", url);
            UserHeadsEntity uh = new UserHeadsEntity()
                    .setUserName(username)
                    .setUserUrl(url)
                    .setUserHeadName(data.getPath())
                    .setCreateTime(DateUtil.date());
            int insert = userHeadersDao.insert(uh);
            flag = insert > 0;
        } else {
            throw new BizException(ResultStatus.HEADER_REPEAT_ERROR);
        }
        if (flag) {
            this.reSetCurrentSession(request, url, null);
        }
        return flag;
    }


    /**
     * 重置缓存数据
     *
     * @param request
     * @param url
     * @param th
     */
    private void reSetCurrentSession(HttpServletRequest request, String url, Teacher th) {
        log.info("重置缓存");
        HttpSession session = request.getSession();
        Teacher teacher = (Teacher) session.getAttribute("teacher");
        session.removeAttribute("teacher");
        if (ObjectUtil.isNull(th)) {
            log.info("修改头像重置缓存");
            teacher.setUserUrl(url);
            session.setAttribute("teacher", teacher);
        } else {
            log.info("用户信息更新重置缓存");
            session.setAttribute("teacher", th);
        }
    }
}
